package com.ruoyi.partybuilding.controller;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.Validation;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.partybuilding.common.*;
import com.ruoyi.partybuilding.domain.*;
import com.ruoyi.partybuilding.domain.vo.ScoreTypeVo;
import com.ruoyi.partybuilding.domain.vo.ScoreYearStatVo;
import com.ruoyi.partybuilding.domain.vo.UserMemberVo;
import com.ruoyi.partybuilding.domain.vo.WorkScoreQueryVo;
import com.ruoyi.partybuilding.service.impl.OrgServiceImpl;
import com.ruoyi.partybuilding.service.impl.WorkScoreServiceImpl;
import lombok.var;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.*;
/**
 * 个人积分Controller
 * 
 * @author he-liangliang@outlook.com
 * @date 2024-11-27
 */
@Api(tags = "积分明细")
@RestController
@RequestMapping("/partybuilding/WorkScore")
public class WorkScoreController extends EQueryController<WorkScore>
{

    @Resource
    WorkScoreServiceImpl workScoreService;

    @ApiOperation(value = "个人规则项得分统计")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:list')")
    @GetMapping("/memberItemStat")
    public R<List<ScoreTypeVo>> memberItemStat(Long year, Long userId,String name) {
        if (year == null || year < 2000 || userId == null || userId < 1)
            return R.fail("查询参数错误");
        var re = workScoreService.memberItemStat(year, userId);
        if (StringUtils.isNotBlank(name)) {
            var list = re.getData().stream().filter(p -> p.getName().contains(name)).collect(Collectors.toList());
            re.setData(list);
        }
        return re;
    }
    @ApiOperation(value = "组织规则项得分统计")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:list')")
    @GetMapping("/orgItemStat")
    public R<List<ScoreTypeVo>> orgItemStat(Long year,Long deptId,String name) {
        if (year == null || year < 2000 || deptId == null || deptId < 1)
            return R.fail("查询参数错误");
        var re = workScoreService.orgItemStat(year, deptId);
        if (StringUtils.isNotBlank(name)) {
            var list = re.getData().stream().filter(p -> p.getName().contains(name)).collect(Collectors.toList());
            re.setData(list);
        }
        return re;
    }
    @ApiOperation(value = "列表总分统计",notes = "默认个人，type=1是组织,支持排序")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:list')")
    @GetMapping("/listStat")
    @DataScope
   public TableDataInfoRows<ScoreYearStatVo> listStat(Long type, ScoreYearStatVo whereObj, PageSort page) {
        if(whereObj.getYearSign()==null||whereObj.getYearSign()<2000)
            return TableDataInfoRows.toFail("查询年份错误");
        if (type == null || type != 1)
            type = 0l;
        if (type == 0) {
            var re = workScoreService.memberYearStat(whereObj, page);
            return toTableDataInfoRows(re);
        }
        var re2 = workScoreService.orgYearStat(whereObj, page);
        return toTableDataInfoRows(re2);
    }



    @Resource
    OrgServiceImpl orgService;

    /**
     * 查询积分列表
     */
    @ApiOperation("列表")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:list')")
    @GetMapping("/list")
    public TableDataInfo list(WorkScore review, PageDomain pageRequest) {
        return super.list(review, pageRequest);
    }

    /**
     * 导出个人积分列表
     */
    @ApiOperation("总列表导出，对应listStat,type：1组织，0党员")
    @PreAuthorize("@ss.hasAnyPermi(@pb.workScore.export+','+@pb.workScore.exportOrg)")
    @Log(title = "积分明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @DataScope
    public void export(HttpServletResponse response, ScoreYearStatVo vo, PageSort pageRequest) {
        if(vo.getType()==null)
            throw new IllegalArgumentException("积分类型错误");
        var re = listStat(vo.getType(), vo, pageRequest);
        if (re.getCode() == 500)
            throw new IllegalArgumentException(re.getMsg());;
        var util = new ExcelUtil<>(ScoreYearStatVo.class);
        var rows= re.getRows();
        for (int i = 0; i < rows.size(); i++) {
            rows.get(i).setIndex(i+1);
        }
        if (vo.getType() == 1)
        {
            util.hideColumn("nickName");
            util.exportExcel(response, re.getRows(), "组织积分数据");
        }
        else
            util.exportExcel(response, re.getRows(), "党员积分数据");

    }

    /**
     * 获取个人积分详细信息
     */
    @ApiOperation("详情")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:query')")
    @GetMapping(value = "/{id}")
    public R<WorkScore> getInfo(@PathVariable("id") Long id) {
        return super.getInfo(id);
    }


    /**
     * 新增个人积分
     */
    @ApiOperation("新增")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:add')")
    @Log(title = "积分明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public R<Long> add(@RequestBody WorkScore review) {
        if(true)
            return R.fail("不开放,使用申请");
        return super.add(review);
    }

    @ApiOperation("个人积分申请列表")
    @PreAuthorize("@ss.hasPermi(@pb.workScore.approve)")
    @Log(title = "积分明细", businessType = BusinessType.INSERT)
    @PostMapping("/approvalList")
    @DataScope
    public TableDataInfoRows<WorkScore> approvalList(PageSort pageSort,@RequestBody WorkScoreQueryVo dto){
       var re= queryHelper.queryable(WorkScore.class)
                .where(p->p.eq(WorkScore::getType,"0")).whereObject(dto)
                .orderByObject(pageSort)
                .toPageResult(pageSort.getPageNum(),pageSort.getPageSize());
       return toTableDataInfoRows(re);
    }
    @ApiOperation("组织积分申请列表")
    @PreAuthorize("@ss.hasAnyPermi(@pb.workScore.approveOrg+','+@pb.workScore.queryOrg)")
    @Log(title = "积分明细", businessType = BusinessType.INSERT)
    @PostMapping("/approvalListOrg")
    @DataScope
    public TableDataInfoRows<WorkScore> approvalListOrg(PageSort pageSort,@RequestBody WorkScoreQueryVo dto){
        var re= queryHelper.queryable(WorkScore.class)
                .where(p->p.eq(WorkScore::getType,"1")).whereObject(dto)
                .orderByObject(pageSort)
                .toPageResult(pageSort.getPageNum(),pageSort.getPageSize());
        return toTableDataInfoRows(re);
    }
    @ApiOperation("积分明细导出，approvalList,type：1组织，0党员")
    //@PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:export')")
    @Log(title = "积分明细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportApproval")
    public void exportApproval(HttpServletResponse response, PageSort pageSort,WorkScoreQueryVo dto) {
        if(dto.getUserId()!=null)
            dto.setType("0");
        else if(dto.getDeptId()!=null)
            dto.setType("1");
        else
            throw new IllegalArgumentException("参数错误");
        TableDataInfoRows<WorkScore> re =null;
        if("1".equals(dto.getType()))
            re=approvalListOrg(pageSort,dto);
        else
            re=approvalList(pageSort,dto);
        if (re.getCode() == 500)
            throw new IllegalArgumentException(re.getMsg());
        var util = new ExcelUtil<>(WorkScore.class);
        if ("1".equals(dto.getType()))
        {
            util.hideColumn("userName");
            util.exportExcel(response, re.getRows(), "组织积分明细");
        }
        else
            util.exportExcel(response, re.getRows(), "党员积分明细");

    }
    @Resource
    Validator validator;
    @ApiOperation("积分申请")
    @PreAuthorize("@ss.hasAnyPermi(@pb.workScore.applyForAdding+','+@pb.workScore.applyForAddingOrg)")
    @Log(title = "积分明细", businessType = BusinessType.INSERT)
    @PostMapping("/applyForAdding")
    public R applyForAdding(@RequestBody  List<WorkScore> dtos) {
        var tids = dtos.stream().map(p -> p.getTitleId()).distinct().collect(Collectors.toList());
        var types = queryHelper.queryable(ScoreType.class).where(p -> p.in(ScoreType::getId, tids)).toList();
        if (types.size() != dtos.size())
            return R.fail("规则无法找到或重复");
        var unifyType = dtos.get(0).getType();
        var unifyYear = dtos.get(0).getYearSign();
        for (var dto : dtos) {
            if (!unifyType.equals(dto.getType()))
                return R.fail("批量-类型错误");
            if (!Objects.equals(unifyYear, dto.getYearSign()))
                return R.fail("批量-年度错误");
            if("0".equals(unifyType)&&dto.getUserId()==null)
                return R.fail("用户积分申请，用户信息不能为空");
            var err=ValidUtil.validToR(dto);
           if(!R.isSuccess(err))
               return  err;
            dto.setId(null);
            dto.setCreatorId(getUserId());
            dto.setCreateTime(new Date());
            dto.setApprovalRecord(null);
            dto.setApprovalRemark(null);
            dto.setApprovalStatus(0l);
        }
        queryHelper.query().insertable(dtos).executeRows();
        return R.ok();
    }

    @ApiOperation(value = "个人积分审批",notes = "approvalStatus：通过设置为1，驳回设置为-1")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:approve')")
    @Log(title = "积分明细", businessType = BusinessType.UPDATE)
    @PostMapping("/approve")
    @DataScope
    public R approve(Boolean isPass,String remark,@RequestBody List<Long> dtoIds) {
        var re=workScoreService.approve(isPass,remark,dtoIds,getUsername());
        if(!R.isSuccess(re))
            re.setMsg("个人积分审批："+re.getMsg());
        return re;
    }
    @ApiOperation(value = "组织积分审批",notes = "approvalStatus：通过设置为1，驳回设置为-1")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:approveOrg')")
    @Log(title = "积分明细", businessType = BusinessType.UPDATE)
    @PostMapping("/approveOrg")
    @DataScope
    public R approveOrg(Boolean isPass,String remark,@RequestBody List<Long> dtoIds) {
        var re=workScoreService.approve(isPass,remark,dtoIds,getUsername());
        if(!R.isSuccess(re))
            re.setMsg("组织积分审批："+re.getMsg());
        return re;
    }

    private void approveSet(WorkScore item, int unifyStatus, String unifyRemark, int maxLevel) {
        if (unifyStatus == 1) {
            var oldStatus = item.getApprovalStatus();
            var arr=JSONUtil.parseArray(item.getApprovalRecord());
            var newStatus = ++oldStatus;
            arr.add(new String[]{DateUtil.now(),getUsername(),newStatus+"", unifyRemark}); //时间，人员，结果,备注
            item.setApprovalStatus(newStatus);
            if (newStatus >= maxLevel) {
                item.setApprovalStatus((long) WorkScore.ApprovalPassEnd);
                arr.add(new String[]{DateUtil.now(),getUsername(),WorkScore.ApprovalPassEnd +"","审批通过完结"});
            }
            var recordStr=JSONUtil.toJsonStr(arr);
            item.setApprovalRecord(recordStr);
            item.setApprovalRemark(unifyRemark);
        }else if(unifyStatus ==-1) {
            var oldStatus = item.getApprovalStatus();
            var arr = JSONUtil.parseArray(item.getApprovalRecord());
            var newStatus = ++oldStatus;
            var newStatusVal=-newStatus;
            arr.add(new String[]{DateUtil.now(), getUsername(), newStatusVal + "", unifyRemark}); //时间，人员，结果,备注
            item.setApprovalStatus(newStatusVal);
            if (newStatus >= maxLevel) {
                item.setApprovalStatus((long) -WorkScore.ApprovalPassEnd);
                arr.add(new String[]{DateUtil.now(),getUsername(),-WorkScore.ApprovalPassEnd +"","审批驳回完结"});
            }
            var recordStr = JSONUtil.toJsonStr(arr);
            item.setApprovalRecord(recordStr);
            item.setApprovalRemark(unifyRemark);
        }
    }

    /**
     * 修改个人积分
     */
    @ApiOperation("编辑")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:edit')")
    @Log(title = "积分明细", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public R<Long> edit(@RequestBody WorkScore review) {
        return super.edit(review);
    }


    /**
     * 删除个人积分
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('partybuilding:WorkScore:remove')")
    @Log(title = "积分明细", businessType = BusinessType.DELETE)
    @PostMapping("remove/{ids}")
    public R<Long> remove(@PathVariable Long[] ids) {
        return super.remove(ids);
    }

}

